package com.ruoyi.web.controller;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.io.FileUtil;
import com.alibaba.excel.EasyExcel;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysDictDataMapper;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.web.domain.dto.WorkFormExcelTemplateDto;
import com.ruoyi.web.domain.importEntity.ImportError;
import com.ruoyi.web.domain.importEntity.ImportResult;
import com.ruoyi.web.excel.WorkFormExcelTemplateListener;
import com.ruoyi.web.service.WorkFormService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.*;

/**
 * description:
 * auth fcb
 * date 2025-06-04 09:19
 **/
@RestController
@RequestMapping("/work-form-excel")
@Slf4j
@Api(tags = "诉求导入")
public class WorkFormExcelController {

    @Autowired
    private WorkFormService workFormService;
    @Autowired
    private DataSourceTransactionManager transactionManager;
    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private SysDeptMapper sysDeptMapper;
    @Autowired
    private SysDictDataMapper sysDictDataMapper;

    @PostMapping("/import")
    @ApiOperation(value = "导入诉求")
    public AjaxResult importWorkFormExcel(@RequestParam("file") MultipartFile file, String problemType) {
        if(file.isEmpty()) {
            return AjaxResult.error("文件为空");
        }
        if(!"xlsx".equalsIgnoreCase(FileUtil.getSuffix(file.getOriginalFilename()))) {
            return AjaxResult.error("文件格式错误");
        }

        WorkFormExcelTemplateListener listener = null;
        ImportResult result = new ImportResult();

        try {
            // 省级部门，约42个
            List<SysDept> deptList = this.getDeptList();
            String createUserId = String.valueOf(SecurityUtils.getUserId());
            listener = new WorkFormExcelTemplateListener(sysDictDataMapper, workFormService, deptList, createUserId, transactionManager, sysDeptMapper, problemType);
            try {
                EasyExcel.read(file.getInputStream(), WorkFormExcelTemplateDto.class, listener).sheet().headRowNumber(3).doRead();
            } catch (Exception e) {
                // Excel读取过程中发生异常，为了继续处理错误信息，在此不直接抛出，而是继续使用监听器收集的错误信息
            }

            // 获取导入结果
            if (listener != null) {
                result = listener.getImportResult();
            }
            // 若 result 为 null，创建一个默认的错误结果
            if (result == null) {
                result = new ImportResult();
                result.setErrorCount(1);
                result.setSuccessCount(0);
                result.setTotalCount(0);
                result.setErrors(Collections.singletonList(new ImportError(-1, "系统", "导入结果为空")));
            }

            if (result.getErrorCount() > 0) {
                // 有导入失败的数据，返回详细错误信息
                Map<String, Object> data = new HashMap<>();
                data.put("successCount", result.getSuccessCount());
                data.put("errorCount", result.getErrorCount());
                data.put("totalCount", result.getTotalCount());
                data.put("errors", result.getErrors());

                String message = String.format("导入完成！成功%d条，失败%d条", result.getSuccessCount(), result.getErrorCount());

                return AjaxResult.success(message, data);
            } else {
                return AjaxResult.success(String.format("导入成功！共导入%d条数据", result.getSuccessCount()));
            }
        } catch (Exception e) {
            log.error("【诉求导入异常】：{}", ExceptionUtil.stacktraceToString(e));

            // 即使发生异常，也尝试返回已收集的错误信息
            Map<String, Object> data = new HashMap<>();

            if (listener != null) {
                ImportResult partialResult = listener.getImportResult();
                if (partialResult != null && partialResult.getErrorCount() != null && partialResult.getErrorCount() > 0) {
                    data.put("successCount", partialResult.getSuccessCount());
                    data.put("errorCount", partialResult.getErrorCount());
                    data.put("totalCount", partialResult.getTotalCount());
                    data.put("errors", partialResult.getErrors());
                } else {
                    // 若 partialResult 为 null，则设置默认值
                    data.put("successCount", 0);
                    data.put("errorCount", 1);
                    data.put("totalCount", 0);
                    data.put("errors", Collections.singletonList(new ImportError(-1, "系统", "导入结果为空")));
                }
            } else {
                // 若 listener 为 null，则设置默认值
                data.put("successCount", 0);
                data.put("errorCount", 1);
                data.put("totalCount", 0);
                data.put("errors", Collections.singletonList(new ImportError(-1, "系统", "监听器初始化失败")));
            }

            data.put("exception", "导入过程发生异常: " + e.getMessage());

            return AjaxResult.success("导入失败: ", data);
        }
    }

    @GetMapping("/downloadTemplateExcel")
    @ApiOperation(value = "下载模板")
    public void downloadTemplateExcel(HttpServletResponse response) {
        try {
            Resource resource = new ClassPathResource("file/工业运行联系服务企业反映问题及建议清单.xlsx");
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + URLEncoder.encode("工业运行联系服务企业反映问题及建议清单.xlsx", "UTF-8"));
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            IOUtils.copy(resource.getInputStream(), response.getOutputStream());
        }catch (Exception e) {
            log.error("【下载模板异常】：{}", ExceptionUtil.stacktraceToString(e));
        }
    }

    // 获取省级部门
    private List<SysDept> getDeptList() {
        SysDept dept = new SysDept();
        dept.setParentId("101");
        return sysDeptService.selectDeptList(dept);
    }
}
